package com.stqf.scala.grammar

import com.alibaba.fastjson.{JSON, JSONObject}

import scala.io.{BufferedSource, Source}

/**
  * Created by ASUS on 2018-01-31.
  */
object HighFunExercise {
  val logName = "custom.log"
  val numberKey: String = "任务生成量"

  def fastJson(line: String): Map[String, Int] = {
    var res: Map[String, Int] = Map[String, Int]()
    val jsonObject: JSONObject = JSON.parseObject(line)
    val value: JSONObject = jsonObject.getJSONObject("detail")
    value.keySet().forEach(key => {
      res = res.++(Map[String, Int](key -> value.getJSONObject(key).getIntValue(numberKey)))
    })
    //res.keys.foreach(k => println(k + "   " + res(k)))
    return res
  }

  def statistics(lists: List[Map[String, Int]]): Unit = {
    var head = lists.head
    lists.tail.foreach(temp => {
      temp.keys.foreach(key => {
        head = head.++(Map[String, Int](key -> (head(key) + temp(key))))
      })
    })
    head.toList.sortBy(temp => temp._2).reverse.foreach(println)
  }

  def main(args: Array[String]): Unit = {
    var file: BufferedSource = null
    try {
      var lists = List[Map[String, Int]]()
      file = Source.fromFile(ClassLoader.getSystemResource(logName).toURI)
      val lines = file.getLines()
      /*if (lines.hasNext) {
        val map = fastJson(lines.next())
        println(map)
      }*/
      while (lines.hasNext) {
        val map = fastJson(lines.next)
        lists = lists :+ map
      }
      statistics(lists)
    } catch {
      case e: Exception => e.printStackTrace()
      case _ => println("未知情况")
    } finally {
      if (file != null)
        file.close()
    }
  }
}
